﻿using ConfExpert.Datasets;
using ConfExpert.Forms.Base;
using DevTeam;
using Kaliko.ImageLibrary;
using Kaliko.ImageLibrary.Filters;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Sistem
{
    public partial class BatchUploadPhoto : XForm
    {
        public BatchUploadPhoto()
        {
            InitializeComponent();
        }

        private void BatchUploadPhoto_Load(object sender, EventArgs e)
        {
            btnBasla.ItemClick += btnBasla_ItemClick;
            btnResize.ItemClick += btnResize_ItemClick;
        }

        void btnResize_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            byte[] Photo2;
            double scaling = 5.0f;

            this.Cursor = Cursors.WaitCursor;
            DataTable dtPhotos = ExecuteDataTable("GetUsersPhoto_Files");

            foreach (DataRow r in dtPhotos.Rows)
            {
                using (Image objImage = ConvertByteArrayToImage((byte[])r["Dosya"]))
                {
                    KalikoImage sharpimg = new KalikoImage(objImage);
                    sharpimg.Resize((int)(sharpimg.Width / scaling), (int)(sharpimg.Height / scaling));
                    sharpimg.ApplyFilter(new UnsharpMaskFilter(1.2F, 0.5F, 20));   //threshold: http://www.damiensymonds.com.au/tut_usm.html
                    using (MemoryStream mstr = new MemoryStream())
                    {
                        sharpimg.SaveJpg(mstr, 95);
                        sharpimg.Dispose();
                        Photo2 = mstr.ToArray();
                    }
                }

                int UserId = r["UserId"].ToInt();
                int UsersPhotoId = r["UsersPhotoId"].ToInt();
                StoreBlob2DataBase(UsersPhotoId, UserId, Photo2);
                GC.Collect();
            }
            this.Cursor = Cursors.Default;
        }

        protected static void StoreBlob2DataBase(int UsersPhotoId, int UserId, byte[] content2)
        {
            SqlConnection con = new SqlConnection(Session.DataManager.ConnectionString);
            con.Open();
            try
            {
                SqlCommand insert = new SqlCommand("UpdUsersPhoto2", con);
                insert.CommandType = CommandType.StoredProcedure;
                //"insert into UserPhotos (UserId, Photo1, Photo2) values (@id, @image1, @image2)", con);
                //"update UserPhotos set Photo2 = @image where UserId = @id", con);
                SqlParameter idParameter1 = insert.Parameters.Add("@UsersPhotoId", SqlDbType.Int);
                idParameter1.Value = UsersPhotoId;
                SqlParameter idParameter2 = insert.Parameters.Add("@UserId", SqlDbType.Int);
                idParameter2.Value = UserId;
                SqlParameter imageParameter2 = insert.Parameters.Add("@Photo2", SqlDbType.Binary);
                imageParameter2.Value = content2;
                imageParameter2.Size = content2.Length;
                insert.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
        }

        void btnBasla_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int x = 0;

            using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
            {
                openFileDialog1.Filter = "JPG Files (*.jpg)|*.jpg";
                openFileDialog1.FilterIndex = 1;
                openFileDialog1.Multiselect = true;

                if (openFileDialog1.ShowDialog() == DialogResult.OK)

                    foreach (string FileName in openFileDialog1.FileNames)
                    {
                        //string FileName = Path.GetFileName(FileName),
                        //    Extension = Path.GetExtension(FileName);

                        FileInfo fi = new FileInfo(FileName);
                        byte[] bArr = FileManager.Read(fi.FullName);

                        MyData.xKaliteKontrolRow r = ds.xKaliteKontrol.NewxKaliteKontrolRow();
                        r.DosyaNo = Path.GetFileNameWithoutExtension(FileName) + Path.GetExtension(FileName);     //fi.Name;
                        //r.DosyaNo = Path.GetFileNameWithoutExtension(FileName) + "^" + Path.GetExtension(FileName);     //fi.Name;
                        //if (r.DosyaNo.Length <= 16)
                        {
                            r.Dosya = bArr;
                            ds.xKaliteKontrol.AddxKaliteKontrolRow(r);
                            if ((++x % 5) == 0)
                            {
                                ExecuteNonQuery("InsUsersPhoto", ds.xKaliteKontrol);

                                ds.xKaliteKontrol.Clear();
                                GC.Collect();
                            }
                        }
                    }

                ExecuteNonQuery("InsUsersPhoto", ds.xKaliteKontrol);
                Notify("Done");

            }
        }

        void btnBasla2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //Save into a file

            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            // Set the help text description for the FolderBrowserDialog.
            folderBrowserDialog1.Description = "Select the directory that you want to upload the contents of.";

            // Do not allow the user to create new files via the FolderBrowserDialog.
            folderBrowserDialog1.ShowNewFolderButton = false;

            // Default to the My Documents folder.
            //this.folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;

            int x = 0;
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                string folderName = folderBrowserDialog1.SelectedPath;

                foreach (string filePath in Directory.GetFiles(folderName, "*.*", SearchOption.AllDirectories))
                {
                    FileInfo fi = new FileInfo(filePath);
                    byte[] bArr = FileManager.Read(fi.FullName);

                    MyData.xKaliteKontrolRow r = ds.xKaliteKontrol.NewxKaliteKontrolRow();
                    r.DosyaNo = Path.GetFileNameWithoutExtension(filePath) + "^" + Path.GetExtension(filePath);     //fi.Name;
                    if (r.DosyaNo.Length <= 16)
                    {
                        r.Dosya = bArr;
                        ds.xKaliteKontrol.AddxKaliteKontrolRow(r);
                        if ((++x % 10) == 0)
                        {
                            ExecuteNonQuery("InsUsersPhoto", ds.xKaliteKontrol);

                            ds.xKaliteKontrol.Clear();
                            GC.Collect();
                        }
                    }
                }

                ExecuteNonQuery("InsUsersPhoto", ds.xKaliteKontrol);
                Notify("Done");
            }
        }


        //void ExecQueryTV(string SP, params object[] p)
        //{
        //    using (SqlConnection sqlConn = new SqlConnection(Session.DataManager.ConnectionString))
        //    {
        //        sqlConn.Open();
        //        SqlCommand sqlCmd = sqlConn.CreateCommand();
        //        sqlCmd.CommandText = SP;
        //        sqlCmd.CommandType = CommandType.StoredProcedure;
        //        SqlParameter[] parameters = new SqlParameter[1];
        //        parameters[0] = new SqlParameter("@tbl", SqlDbType.Structured);
        //        parameters[0].Value = p[0];
        //        sqlCmd.Parameters.Add(parameters[0]);
        //        sqlCmd.ExecuteNonQuery();
        //    }
        //}


        /*
         * Save
MemoryStream stream = Serializer.SerializeToStream(car);            
System.IO.File.WriteAllBytes(fileName, stream.ToArray());

    //Load from a file
using (var stream = new MemoryStream(System.IO.File.ReadAllBytes(fileName)))
Car car = (Car)Serializer.DeserializeFromStream(stream);
           
    

public static byte[] StreamToByteArray(Stream stream)
{
    if (stream is MemoryStream)
    {
        return ((MemoryStream)stream).ToArray();
    }
    else
    {
        // Jon Skeet's accepted answer 
        return ReadFully(stream);
    }
    return null;
}

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}
*/
    }
}

